﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Criterion;

namespace DocuServe.Data
{
    public class Repository<T> where T : class
    {
        public void Delete(T obj)
        {
            using (RepositoryScope scope = RepositoryScope.Start())
            {
                ISession session = SessionManager.GetCurrentSession();
                session.Delete(obj);
                scope.Commit();
            }
        }

        public T GetByID(object id)
        {
            using (RepositoryScope scope = RepositoryScope.Start())
            {
                ISession session = SessionManager.GetCurrentSession();
                return session.Get<T>(id);
            }
        }

        public IList<T> List()
        {
            return this.List(DetachedCriteria.For<T>());
        }

        public IList<T> List(DetachedCriteria criteria)
        {
            using (RepositoryScope scope = RepositoryScope.Start())
            {
                ISession session = SessionManager.GetCurrentSession();
                return criteria.GetExecutableCriteria(session).List<T>();
            }
        }

        public void Save(T obj)
        {
            using (RepositoryScope scope = RepositoryScope.Start())
            {
                ISession session = SessionManager.GetCurrentSession();
                session.SaveOrUpdate(obj);
                scope.Commit();
            }
        }
    }
}
